import React, { useState } from 'react';
import { 
  Plus, Upload, FileSpreadsheet, Save, X, Check,
  Calendar, MapPin, Zap, Factory, Car, AlertCircle
} from 'lucide-react';

const DataEntry = () => {
  const [activeTab, setActiveTab] = useState('manual');
  const [formData, setFormData] = useState({
    category: '',
    indicator: '',
    value: '',
    unit: '',
    period: '',
    location: '',
    source: '',
    description: ''
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);

  // 数据分类配置
  const categories = [
    { id: 'environment', name: '环境(E)', icon: Zap, color: 'green' },
    { id: 'social', name: '社会(S)', icon: Factory, color: 'blue' },
    { id: 'governance', name: '治理(G)', icon: Car, color: 'purple' }
  ];

  // 指标配置
  const indicators = {
    environment: [
      { id: 'carbon_emission', name: '碳排放量', unit: 'tCO2e' },
      { id: 'energy_consumption', name: '能源消耗', unit: 'kWh' },
      { id: 'water_usage', name: '用水量', unit: '立方米' },
      { id: 'waste_generation', name: '废物产生量', unit: '吨' }
    ],
    social: [
      { id: 'employee_count', name: '员工总数', unit: '人' },
      { id: 'training_hours', name: '培训时长', unit: '小时' },
      { id: 'safety_incidents', name: '安全事故数', unit: '次' },
      { id: 'diversity_ratio', name: '多元化比例', unit: '%' }
    ],
    governance: [
      { id: 'board_meetings', name: '董事会会议次数', unit: '次' },
      { id: 'compliance_score', name: '合规得分', unit: '分' },
      { id: 'audit_findings', name: '审计发现问题数', unit: '个' },
      { id: 'transparency_index', name: '透明度指数', unit: '分' }
    ]
  };

  const handleInputChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    
    // 自动填充单位
    if (field === 'indicator') {
      const allIndicators = Object.values(indicators).flat();
      const selectedIndicator = allIndicators.find(ind => ind.id === value);
      if (selectedIndicator) {
        setFormData(prev => ({ ...prev, unit: selectedIndicator.unit }));
      }
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    
    // 模拟API调用
    setTimeout(() => {
      setIsSubmitting(false);
      alert('数据提交成功！');
      setFormData({
        category: '',
        indicator: '',
        value: '',
        unit: '',
        period: '',
        location: '',
        source: '',
        description: ''
      });
    }, 2000);
  };

  const handleFileUpload = (e) => {
    const file = e.target.files[0];
    if (file) {
      setUploadProgress(0);
      // 模拟上传进度
      const interval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev >= 100) {
            clearInterval(interval);
            alert('文件上传成功！');
            return 100;
          }
          return prev + 10;
        });
      }, 200);
    }
  };

  const getCurrentIndicators = () => {
    return formData.category ? indicators[formData.category] || [] : [];
  };

  return (
    <div className="p-6 max-w-7xl mx-auto">
      {/* 页面标题 */}
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-900">数据录入</h2>
        <p className="text-gray-600">录入和管理ESG相关数据</p>
      </div>

      {/* 标签切换 */}
      <div className="mb-6">
        <div className="border-b border-gray-200">
          <nav className="-mb-px flex space-x-8">
            <button
              onClick={() => setActiveTab('manual')}
              className={`py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === 'manual'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
            >
              手动录入
            </button>
            <button
              onClick={() => setActiveTab('batch')}
              className={`py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === 'batch'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
            >
              批量导入
            </button>
          </nav>
        </div>
      </div>

      {/* 手动录入表单 */}
      {activeTab === 'manual' && (
        <div className="bg-white rounded-lg shadow-md p-6">
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* 数据分类 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  数据分类 *
                </label>
                <select
                  value={formData.category}
                  onChange={(e) => handleInputChange('category', e.target.value)}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
                >
                  <option value="">请选择分类</option>
                  {categories.map(cat => (
                    <option key={cat.id} value={cat.id}>{cat.name}</option>
                  ))}
                </select>
              </div>

              {/* 指标名称 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  指标名称 *
                </label>
                <select
                  value={formData.indicator}
                  onChange={(e) => handleInputChange('indicator', e.target.value)}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
                  disabled={!formData.category}
                >
                  <option value="">请选择指标</option>
                  {getCurrentIndicators().map(ind => (
                    <option key={ind.id} value={ind.id}>{ind.name}</option>
                  ))}
                </select>
              </div>

              {/* 数值 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  数值 *
                </label>
                <input
                  type="number"
                  step="0.01"
                  value={formData.value}
                  onChange={(e) => handleInputChange('value', e.target.value)}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入数值"
                  required
                />
              </div>

              {/* 单位 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  计量单位
                </label>
                <input
                  type="text"
                  value={formData.unit}
                  onChange={(e) => handleInputChange('unit', e.target.value)}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-50 focus:outline-none"
                  placeholder="自动填充"
                  readOnly
                />
              </div>

              {/* 报告期间 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  报告期间 *
                </label>
                <input
                  type="month"
                  value={formData.period}
                  onChange={(e) => handleInputChange('period', e.target.value)}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
                />
              </div>

              {/* 数据来源位置 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  数据来源位置 *
                </label>
                <select
                  value={formData.location}
                  onChange={(e) => handleInputChange('location', e.target.value)}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
                >
                  <option value="">请选择位置</option>
                  <option value="headquarters">总部</option>
                  <option value="factory_a">工厂A</option>
                  <option value="factory_b">工厂B</option>
                  <option value="branch_office">分公司</option>
                  <option value="warehouse">仓库</option>
                </select>
              </div>
            </div>

            {/* 数据来源 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                数据来源说明 *
              </label>
              <input
                type="text"
                value={formData.source}
                onChange={(e) => handleInputChange('source', e.target.value)}
                className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="例如：电费账单、设备监测报告等"
                required
              />
            </div>

            {/* 备注描述 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                备注描述
              </label>
              <textarea
                value={formData.description}
                onChange={(e) => handleInputChange('description', e.target.value)}
                rows={3}
                className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="可选的补充说明..."
              />
            </div>

            {/* 数据预览 */}
            {formData.value && formData.indicator && (
              <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
                <div className="flex items-center mb-2">
                  <AlertCircle className="h-5 w-5 text-blue-600 mr-2" />
                  <span className="font-medium text-blue-900">数据预览</span>
                </div>
                <p className="text-blue-800">
                  将录入：{getCurrentIndicators().find(ind => ind.id === formData.indicator)?.name} = {formData.value} {formData.unit}
                </p>
              </div>
            )}

            {/* 提交按钮 */}
            <div className="flex justify-end space-x-4">
              <button
                type="button"
                className="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50"
                onClick={() => setFormData({
                  category: '',
                  indicator: '',
                  value: '',
                  unit: '',
                  period: '',
                  location: '',
                  source: '',
                  description: ''
                })}
              >
                重置
              </button>
              <button
                type="submit"
                disabled={isSubmitting}
                className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center"
              >
                {isSubmitting ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                    提交中...
                  </>
                ) : (
                  <>
                    <Save className="h-4 w-4 mr-2" />
                    保存数据
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      )}

      {/* 批量导入 */}
      {activeTab === 'batch' && (
        <div className="space-y-6">
          {/* 上传区域 */}
          <div className="bg-white rounded-lg shadow-md p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">文件上传</h3>
            
            <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center">
              <Upload className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <div className="space-y-2">
                <p className="text-lg font-medium text-gray-900">
                  拖拽文件到此处或点击上传
                </p>
                <p className="text-sm text-gray-500">
                  支持 Excel (.xlsx) 和 CSV (.csv) 格式，最大文件大小 10MB
                </p>
              </div>
              
              <input
                type="file"
                accept=".xlsx,.xls,.csv"
                onChange={handleFileUpload}
                className="hidden"
                id="file-upload"
              />
              <label
                htmlFor="file-upload"
                className="mt-4 inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 cursor-pointer"
              >
                <FileSpreadsheet className="h-4 w-4 mr-2" />
                选择文件
              </label>
            </div>

            {/* 上传进度 */}
            {uploadProgress > 0 && uploadProgress < 100 && (
              <div className="mt-4">
                <div className="flex items-center justify-between text-sm text-gray-600 mb-1">
                  <span>上传进度</span>
                  <span>{uploadProgress}%</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div
                    className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                    style={{ width: `${uploadProgress}%` }}
                  ></div>
                </div>
              </div>
            )}
          </div>

          {/* 模板下载 */}
          <div className="bg-white rounded-lg shadow-md p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">导入模板</h3>
            <p className="text-gray-600 mb-4">
              请下载标准模板，按照模板格式填写数据后上传
            </p>
            
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {categories.map(cat => {
                const Icon = cat.icon;
                return (
                  <div key={cat.id} className="border border-gray-200 rounded-lg p-4">
                    <div className="flex items-center mb-3">
                      <div className={`p-2 rounded-lg mr-3 ${
                        cat.color === 'green' ? 'bg-green-100 text-green-600' :
                        cat.color === 'blue' ? 'bg-blue-100 text-blue-600' :
                        'bg-purple-100 text-purple-600'
                      }`}>
                        <Icon className="h-5 w-5" />
                      </div>
                      <span className="font-medium text-gray-900">{cat.name}</span>
                    </div>
                    <button className="w-full text-sm text-blue-600 hover:text-blue-800 border border-blue-200 rounded px-3 py-2 hover:bg-blue-50">
                      下载模板
                    </button>
                  </div>
                );
              })}
            </div>
          </div>

          {/* 数据验证规则 */}
          <div className="bg-white rounded-lg shadow-md p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">数据验证规则</h3>
            <div className="space-y-3 text-sm text-gray-600">
              <div className="flex items-start">
                <Check className="h-4 w-4 text-green-600 mr-2 mt-0.5 flex-shrink-0" />
                <span>数值字段必须为有效数字，不能包含文字</span>
              </div>
              <div className="flex items-start">
                <Check className="h-4 w-4 text-green-600 mr-2 mt-0.5 flex-shrink-0" />
                <span>日期格式必须为 YYYY-MM-DD</span>
              </div>
              <div className="flex items-start">
                <Check className="h-4 w-4 text-green-600 mr-2 mt-0.5 flex-shrink-0" />
                <span>数据分类必须为：environment, social, governance</span>
              </div>
              <div className="flex items-start">
                <Check className="h-4 w-4 text-green-600 mr-2 mt-0.5 flex-shrink-0" />
                <span>必填字段不能为空</span>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default DataEntry; 